<template>
  <div class="blog-post-container">
    <!-- Banner 骨架屏或内容 -->
    <SkeletonLoader v-if="loading.banner" type="banner" />
    <BannerCarousel v-else :options="bannerImage" :slidesPerView="1" />

    <section class="blog-post-content">
      <!--   显示最新两条博客 -->
      <!-- <div class="brand-news-section">
        <SkeletonLoader v-if="loading.latestNews" type="news" :count="2" :showLogo="true" />
        <NewsCarousel v-else title="BRAND NEWS" :newsItems="latestNews" :moreLink="`/blog-left-menu`"
          moreLinkText="Read more" :showLogo="true" :autoplay="false" :loop="false" :pagination="false"
          :maxDesktopSlides="2" />
      </div> -->

      <!-- 品牌新闻 骨架屏或内容 -->
      <div class="brand-news-section" v-if="boldNavList.length > 4 || loading.journey">
        <SkeletonLoader v-if="loading.brandNews" type="news" :count="2" :showLogo="true" />
        <NewsCarousel v-else :title="boldNavList[4]?.name" :newsItems="brandNews" :moreLink="`/blog-left-menu`"
          moreLinkText="Read more" :showLogo="true" :autoplay="false" :loop="false" :pagination="false"
          :maxDesktopSlides="2" />
      </div>

      <!-- 歌莉娅的旅程 骨架屏或内容 -->
      <div class="goelia-journey-section" v-if="boldNavList.length > 0 || loading.journey">
        <SkeletonLoader v-if="loading.journey" type="journey" :count="3" />
        <JourneyCarousel v-else :title="boldNavList[0]?.name" :journeyItems="journeyItems" :moreLink="`/blog-left-menu`"
          :autoplay="false" :loop="false" :pagination="false" :maxDesktopSlides="3" />
      </div>
    </section>

    <!-- 中间Banner 骨架屏或内容 -->
    <SkeletonLoader v-if="loading.banner" type="banner" />
    <BannerCarousel v-else :options="bannerImage2" :slidesPerView="1" />

    <section class="blog-post-content">
      <!-- 风格灵感 骨架屏或内容 -->
      <div class="goelia-journey-section" v-if="boldNavList.length > 1 || loading.styleInspiration">
        <SkeletonLoader v-if="loading.styleInspiration" type="journey" :count="3" />
        <JourneyCarousel v-else :title="boldNavList[1]?.name" :journeyItems="styleInspiration"
          :moreLink="`/blog-left-menu`" :autoplay="false" :loop="false" :pagination="false" :maxDesktopSlides="3" />
      </div>

      <!-- 适配与保养 骨架屏或内容 -->
      <div class="brand-news-section" v-if="boldNavList.length > 2 || loading.fitCare">
        <SkeletonLoader v-if="loading.fitCare" type="news" :count="2" :showLogo="true" />
        <NewsCarousel v-else :title="boldNavList[2]?.name" :newsItems="fitCare" :moreLink="`/blog-left-menu`"
          moreLinkText="Read more" :showLogo="true" :autoplay="false" :loop="false" :pagination="false"
          :maxDesktopSlides="2" />
      </div>

      <!-- 时尚技巧 骨架屏或内容 -->
      <div class="goelia-journey-section" v-if="boldNavList.length > 3 || loading.fashionTips">
        <SkeletonLoader v-if="loading.fashionTips" type="journey" :count="3" />
        <JourneyCarousel v-else :title="boldNavList[3]?.name" :journeyItems="fashionTips" :moreLink="`/blog-left-menu`"
          :autoplay="false" :loop="false" :pagination="false" :maxDesktopSlides="3" />
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
// @ts-ignore
import BannerCarousel from '../Home/components/BannerCarousel.vue';
// 导入Swiper相关组件和模块
import { Swiper, SwiperSlide } from 'swiper/vue';
import { Autoplay, Pagination, Navigation } from 'swiper/modules';
// @ts-ignore
import 'swiper/css';
// @ts-ignore
import 'swiper/css/pagination';
// @ts-ignore
import 'swiper/css/navigation';
import { defineAsyncComponent } from 'vue';
import { getnav, getnavList, getnewList, getsidebar, getdetail } from '@/api/blog'
import SkeletonLoader from './components/SkeletonLoader.vue';

// 异步导入NewsCarousel组件
const NewsCarousel = defineAsyncComponent(() => import('@/views/BlogPost/components/NewsCarousel.vue'));

// 导入JourneyCarousel组件
const JourneyCarousel = defineAsyncComponent(() => import('@/views/BlogPost/components/JourneyCarousel.vue'));

// 添加具名导出
defineOptions({
  name: 'BlogPost'
})

// 加载状态
const loading = reactive<{
  banner: boolean;
  brandNews: boolean;
  journey: boolean;
  styleInspiration: boolean;
  fitCare: boolean;
  fashionTips: boolean;
  latestNews: boolean;
  [key: string]: boolean;
}>({
  banner: true,
  brandNews: true,
  journey: true,
  styleInspiration: true,
  fitCare: true,
  fashionTips: true,
  latestNews: true
});

// Swiper模块
const SwiperAutoplay = Autoplay;
const SwiperPagination = Pagination;
const SwiperNavigation = Navigation;

// 响应式slide数量
const slidesPerView = ref(2);

// 更新每个视图显示的slide数量
const updateSlidesPerView = () => {
  if (window.innerWidth <= 768) {
    slidesPerView.value = 1;
  } else {
    slidesPerView.value = 2;
  }
};

// 定义博客数据项接口
interface BlogItem {
  id?: string | number;
  title: string;
  date?: string;
  image: string;
  link: string;
  thumbnail?: string;
  header_image?: string;
  published_at?: string;
}

// 监听窗口大小变化
onMounted(() => {
  updateSlidesPerView();
  window.addEventListener('resize', updateSlidesPerView);
});

onUnmounted(() => {
  window.removeEventListener('resize', updateSlidesPerView);
});

const bannerImage = ref<BlogItem[]>([])
const bannerImage2 = ref<BlogItem[]>([])
const latestNews = ref<BlogItem[]>([])
const boldNavList = ref<{ id: string | number; name: string }[]>([])
const journeyItems = ref<BlogItem[]>([]);
const styleInspiration = ref<BlogItem[]>([]);
const fitCare = ref<BlogItem[]>([]);
const fashionTips = ref<BlogItem[]>([]);
const brandNews = ref<BlogItem[]>([]);

// 博客导航
const getnavFn = async () => {
  try {
    // 0 获取全部博客，用来渲染轮播图
    const res = await getnavList(0)
    // 处理 banner 数据
    if (res.code === 200) {
      if (res.data?.length > 0 && res.data[0].list?.length > 0) {
        let headerImageArr:any = []
        res.data[0].list.forEach((item: any, index: number) => {
          
          if (item.header_image && item.header_image !== "") {
            headerImageArr.push(item)
          }

        })

        headerImageArr.forEach((item: any, index: number) => {
          // 第一组
          if (index < 5) {
            bannerImage.value.push({
              image: item.header_image,
              title: item.title,
              link: '/blog-left-menu',
            })
          }
          // 第二组
          if (index >= 5) {
            bannerImage2.value.push({
              image: item.header_image,
              title: item.title,
              link: '/blog-left-menu',
              ...item
            })
          }
        })
      }
      loading.banner = false;
    }
  } catch (error) {
    console.error('Failed to load banner data:', error);
    loading.banner = false;
  }

  // try {
  //   // 最新两条博客
  //   const res2 = await getnewList()
  //   if (res2.code === 200) {
  //     if (res2.data?.length > 0) {
  //       latestNews.value = res2.data
  //         .map((item: any) => ({
  //           title: item.title,
  //           date: item.published_at,
  //           image: item.thumbnail,
  //           link: '/blog-left-menu'
  //         }))
  //     }
  //     loading.latestNews = false;
  //   }
  // } catch (error) {
  //   console.error('Failed to load brand news:', error);
  //   loading.latestNews = false;
  // }

  try {
    // 博客导航
    const navList = await getnav()
    if (navList.code === 200) {
      boldNavList.value = navList.data

      // 获取各个分类下的博客数据
      await Promise.all([
        loadJourneyItems(),
        loadStyleInspiration(),
        loadFitCare(),
        loadFashionTips(),
        loadBrandNews()
      ]);
    }
  } catch (error) {
    console.error('Failed to load navigation:', error);
    // 设置所有加载状态为false，显示空状态UI
    Object.keys(loading).forEach(key => {
      loading[key] = false;
    });
  }
}

// 加载"歌莉娅的旅程"数据
const loadJourneyItems = async () => {
  loading.journey = true;
  try {
    if (boldNavList.value.length > 0) {
      const navres = await getnavList(boldNavList.value[0].id)
      if (navres.code === 200) {
        if (navres.data?.length > 0 && navres.data[0].list?.length > 0) {
          journeyItems.value = navres.data[0].list.map((item: any) => ({
            image: item.thumbnail,
            title: item.title,
            link: '/blog-left-menu',
            ...item
          }))
        }
      }
    }
  } catch (error) {
    console.error('Failed to load journey items:', error);
  } finally {
    loading.journey = false;
  }
}

// 加载"风格灵感"数据
const loadStyleInspiration = async () => {
  loading.styleInspiration = true;
  try {
    if (boldNavList.value.length > 1) {
      const navres2 = await getnavList(boldNavList.value[1].id)
      if (navres2.code === 200) {
        if (navres2.data?.length > 0 && navres2.data[0].list?.length > 0) {
          styleInspiration.value = navres2.data[0].list.map((item: any) => ({
            image: item.thumbnail,
            title: item.title,
            link: '/blog-left-menu',
            ...item
          }))
        }
      }
    }
  } catch (error) {
    console.error('Failed to load style inspiration:', error);
  } finally {
    loading.styleInspiration = false;
  }
}

// 加载"适配与保养"数据
const loadFitCare = async () => {
  loading.fitCare = true;
  try {
    if (boldNavList.value.length > 2) {
      const navres3 = await getnavList(boldNavList.value[2].id)
      if (navres3.code === 200) {
        if (navres3.data?.length > 0 && navres3.data[0].list?.length > 0) {
          fitCare.value = navres3.data[0].list.map((item: any) => ({
            image: item.thumbnail,
            title: item.title,
            link: '/blog-left-menu',
            ...item
          }))
        }
      }
    }
  } catch (error) {
    console.error('Failed to load fit care:', error);
  } finally {
    loading.fitCare = false;
  }
}

// 加载"时尚技巧"数据
const loadFashionTips = async () => {
  loading.fashionTips = true;
  try {
    if (boldNavList.value.length > 3) {
      const navres4 = await getnavList(boldNavList.value[3].id)
      if (navres4.code === 200) {
        if (navres4.data?.length > 0 && navres4.data[0].list?.length > 0) {
          fashionTips.value = navres4.data[0].list.map((item: any) => ({
            image: item.thumbnail,
            title: item.title,
            link: '/blog-left-menu',
            ...item
          }))
        }
      }
    }
  } catch (error) {
    console.error('Failed to load fashion tips:', error);
  } finally {
    loading.fashionTips = false;
  }
}

//加载品牌新闻
const loadBrandNews = async () => {
  loading.brandNews = true;
  try {
    if (boldNavList.value.length > 4) {
      const navres5 = await getnavList(boldNavList.value[4].id)
      if (navres5.code === 200) {
        if (navres5.data?.length > 0 && navres5.data[0].list?.length > 0) {
          brandNews.value = navres5.data[0].list.map((item: any) => ({
            image: item.thumbnail,
            title: item.title,
            link: '/blog-left-menu',
            ...item
          }))
        }
      }
    }
  } catch (error) {
    console.error('Failed to load fashion tips:', error);
  } finally {
    loading.brandNews = false;
  }
}

// 如果图片不存在，可以添加默认图片逻辑
onMounted(() => {
  // 在这里可以添加处理图片加载错误的逻辑
  getnavFn()
})
</script>

<style lang="scss" scoped>
:deep(.swiper-item img) {
  // height: 651px !important;
  aspect-ratio: 3 / 1 !important;
}

:deep(.swiper-pagination-bullets.swiper-pagination-horizontal) {
  bottom: 20px !important;
}

:deep(.swiper-pagination-bullet) {
  width: 12px !important;
  height: 12px !important;
  background: #fff;
  margin: 0 5px !important;
}

.blog-post-container {
  width: 100%;

  .blog-post-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 40px 0px;
  }
}


.blog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 40px 0 20px;
  border-bottom: 1px solid #e5e5e5;
  padding-bottom: 10px;

  h1 {
    font-size: 24px;
    font-weight: 600;
    margin: 0;
  }

  .read-more-link {
    font-size: 14px;
    color: #232323;
    text-decoration: none;
    transition: all 0.3s ease;

    &:hover {
      text-decoration: underline;
    }
  }
}

.blog-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 30px;
  margin-bottom: 50px;

  @media (max-width: 1024px) {
    grid-template-columns: repeat(2, 1fr);
  }

  @media (max-width: 768px) {
    grid-template-columns: 1fr;
  }
}

.blog-card {
  cursor: pointer;
  transition: transform 0.3s ease;

  &:hover {
    transform: translateY(-5px);
  }

  .blog-image {
    width: 100%;
    height: 240px;
    overflow: hidden;
    margin-bottom: 15px;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.5s ease;
    }

    &:hover img {
      transform: scale(1.05);
    }
  }

  .blog-content {
    padding: 0 5px;

    .blog-title {
      font-size: 16px;
      font-weight: 500;
      margin: 0 0 8px;
      line-height: 1.4;
      color: #232323;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .blog-date {
      font-size: 14px;
      color: #777;
      margin: 0;
    }
  }
}

.newsletter-section {
  background-color: #f9f9f9;
  padding: 40px;
  text-align: center;
  margin-top: 50px;

  h2 {
    font-size: 22px;
    margin-bottom: 10px;
  }

  p {
    font-size: 14px;
    color: #555;
    margin-bottom: 20px;
  }

  .newsletter-form {
    display: flex;
    max-width: 450px;
    margin: 0 auto;

    input {
      flex: 1;
      padding: 12px 15px;
      border: 1px solid #ddd;
      font-size: 14px;
      outline: none;

      &:focus {
        border-color: #333;
      }
    }

    button {
      background-color: #232323;
      color: white;
      border: none;
      padding: 0 25px;
      cursor: pointer;
      font-size: 14px;
      font-weight: 500;
      transition: background-color 0.3s ease;

      &:hover {
        background-color: #000;
      }
    }
  }

  @media (max-width: 768px) {
    padding: 30px 20px;

    .newsletter-form {
      flex-direction: column;

      input {
        margin-bottom: 10px;
      }

      button {
        padding: 12px 25px;
      }
    }
  }
}

/* 额外的响应式调整 */
@media (max-width: 768px) {
  .blog-post-container {
    padding: 20px 15px;
  }

  .blog-header h1 {
    font-size: 20px;
  }

  .blog-card .blog-image {
    height: 200px;
  }

  .journey-section {
    margin-bottom: 0;
  }

  .blog-post-container .blog-post-content {
    padding: 0;
  }

  .swiper-container,
  .common-container {
    margin-bottom: 20px;
  }
}

@media (max-width: 480px) {
  .blog-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .blog-card .blog-image {
    height: 180px;
  }
}

.brand-news-section {
  max-width: 1200px;
  margin: 0 auto;
  position: relative;
  padding: 0 20px;
}

.goelia-journey-section {
  max-width: 1200px;
  margin: 0 auto;
  position: relative;
  padding: 0 20px;
}
</style>